class Solution {
public:
    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
        int m = mat.size(); int n = mat[0].size();
        map<int, pair<int, int>> mp;
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                mp[mat[i][j]] = make_pair(i, j);

        vector<int> c(n), r(m);
        for (int k = 0; k < m * n; ++k)
        {
            r[mp[arr[k]].first]++;
            if (r[mp[arr[k]].first] == n)
                return k;
            c[mp[arr[k]].second]++;
            if (c[mp[arr[k]].second] == m)
                return k;
        }
        return 0;
    }
};